<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="入库明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                    <el-form :model="basicForm" :label-width="formLabelWidth"
                      ref="ruleForm"
                             :rules="rules"
                             class="demo-ruleForm"
                    >
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="入库编号：">
                                    <span>{{ basicForm.billNo }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="机构：">
                                   <span>{{ basicForm.orgName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="业务类型：" prop="businessTypeKey">
                                      <el-select v-model="basicForm.businessTypeKey"
                                         @change="changeBusinessType"
                                    >
                                        <el-option v-for="item in businessTypeArr" :key="item.id" :value="item.id"
                                        :label="item.name"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="源单编号：" :prop="this.basicForm.businessTypeKey == 6?'':'sourceNo'">
                                       <el-input v-model="basicForm.sourceNo" readonly>

                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="clickSingle"></i>

                                       </el-input>
                                   <el-button class="a" @click="linkToSouce">查看</el-button>
                                </el-form-item>

                            </el-col>
                        </el-row>

                        <el-row>
                             <el-col :span="12">
                                <el-form-item label="供方：" prop="supplierName">
                                  <el-input v-model="basicForm.supplierName">
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy" @click="generalSelectOuter"></i>
                                  </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="采购人员：">
                                      <el-input v-model="basicForm.purchaserName" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"  @click="selectName" ></i>
                                            </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="入库日期：">
                                     <el-date-picker
                                        value-format="yyyy-MM-dd"
                                        :clearable="false"
                                        type="date"
                                        placeholder="选择日期"
                                        v-model="basicForm.warehousingDate"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="收料人员：">
                                   <el-input v-model="basicForm.receivingPersonnelName" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"  @click="selectreceivingPersonnelName" ></i>
                                            </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="备注：">
                                    <el-input
                                        type="textarea"
                                        v-model="basicForm.remarks"
                                        autocomplete="off"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="数量：">
                                   <span>

                                       {{
                                           basicForm.totalQuantity
                                       }}
                                   </span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                             <el-row>

                            <el-col :span="12">
                                <el-form-item label="状态：">
                                    <span>{{ statusLable(basicForm.state)}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                    </el-form>
                        </div>
                    </div>
                    <!-- 入库明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">入库明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <el-button size="mini" type="primary"
                                        @click="clickSingle"
                                        v-if="this.basicForm.businessTypeKey != 6"
                                        >选择物资</el-button
                                    >
                                    <el-button size="mini" type="primary"
                                        v-else
                                        @click="clickBase"
                                        >选择基础库</el-button
                                    >
                                </div>
                            </div>
                        <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <!-- <span>
                                {{
                                  test
                                }}
                            </span> -->
                            <el-table
                                 class="table"
                                :data="detailedTableDataComputed"
                                border
                                style="width: 100%"
                                 default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                 :max-height="$store.state.tableHeight"
                                :row-class-name="tableRowClassName"
                                 v-sortTable="{ 'tableData': detailedTableDataComputed, '_this': this, 'ref': 'multipleTable' }"
                            >
                         <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >

                                   <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div style="cursor: pointer">
                                                <img
                                                v-if="$index > 0"
                                                    src="@/assets/btn/delete.png"
                                                    @click="
                                                        deleteEle(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>

                                </el-table-column>
                                  <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    mini-width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="材质"
                                    width="200"
                                >
                                <template slot-scope="{row,$index}">
                                    <el-input v-model="row.texture" v-if="$index>0"
                                            @input="curStateChange(row)"
                                        >
                                    </el-input>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                    width="200"
                                >
                                    <template slot-scope="{row,$index}">
                                    <span v-if="$index>0">
                                        {{
                                            row.warehouseName
                                        }}
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="receiptQuantity"
                                    label="入库数量"
                                    width="200"
                                >
                                <template slot-scope="{row,$index}">
                                    <el-input v-model="row.receiptQuantity" v-if="$index>0"
                                            @input="curStateChange(row)"

                                        >

                                    </el-input>
                                </template>
                                </el-table-column>
                                <el-table-column

                                    prop="timeUnit"
                                    label="计时单位"
                                    width="200"
                                    v-if="isLease"
                                >
                                 <template slot-scope="{ row, $index }">
                                        <el-select
                                            v-model="row.timeUnit"
                                            placeholder="请选择"
                                            @chenge="curStateChange(row)"
                                            v-if="$index > 0"
                                        >
                                            <el-option
                                                v-for="item in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseTime"
                                    label="租赁时间"
                                    width="200"
                                    v-if="isLease"

                                >
                                    <template slot-scope="{row,$index}">
                                    <el-input v-model="row.leaseTime" v-if="$index>0"
                                            @chenge="curStateChange(row)"

                                        >

                                    </el-input>
                                </template>
                                </el-table-column>

                            </el-table>
                        </div>

                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                      <attach-comp :relationId="attachId" bucketName="turnover" />

                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                             <ComAuditHistoryIndex
                                :billType="6070"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>

                </div>
            </el-tabs>
        </div>
   <div class="buttons">

            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>

            <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId" />
            <el-button size="small" @click="handleClose">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import { openAppClient, getUuid, showLoading, hideLoading } from '@/utils/common'
// import { getUuid } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import auditRequest from '@/api/turnover/audit.js'
import otherRequest from '@/api/turnover/other.js'
import { selectName, setTurnoverSelectInstockMaterials, categoryLibrary, GeneralSelectOuter } from '@/api/turnover/ppw.js'
import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit, deleteLogic, detailedTableDataComputed  } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import { doChildren } from '@/api/turnover/utils.js'
import { mapState } from 'vuex'
// import fn  from '@/utils/checkEmpty.js'
import { mapMutations } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            businessTypeArr: state=>state.turnover.turnoverData.businessTypeArr,
        }),
        isLease () {
            if(this.basicForm.businessTypeKey == 3 || this.basicForm.businessTypeKey == 5) {
                return true
            }else{
                return false
            }
        },
        detailedTableDataComputed () {
            return detailedTableDataComputed(this.detailedTableData)
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'detailed',
            'attach',
            'auditHistory',
        ]
        this.tabArr = arr  //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    created () {
        this.billId = this.$route.query.billid

        this.init()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基础信息
            basicForm: {
                'billId': '',
                'billNo': '',
                'businessTypeKey': '',
                'businessTypeValue': '',
                'isRed': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'parentId': '',
                'purchaserId': '',
                'purchaserName': '',
                'receivingPersonnelId': '',
                'receivingPersonnelName': '',
                'remarks': '',
                'sourceId': '',
                'sourceNo': '',
                'state': 0,
                'supplierId': '',
                'supplierName': '',
                'totalQuantity': 0,
                'warehousingDate': '',
                'workId': ''
            },
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            tableData: [],
            changeTableData: [],
            basicInfo: {},
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: [],
            },
            yearNeedPlanList: [],
            selectContro: [
                { id: 0, name: '申报机构汇总' },
                { id: 1, name: '物资汇总' },
            ],
            showConnect: 0,
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6070,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            rules: {
                businessTypeKey: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'chenge'
                    }
                ],
                sourceNo: [
                    {
                        required: true,
                        message: '请选择源单编号',
                        trigger: 'blur'
                    }
                ],
                supplierName: [
                    {
                        required: true,
                        message: '请选择供方',
                        trigger: 'blur'
                    }
                ],
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            curRow: {},
            test: ''
        }
    },
    methods: {

        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        // 选择供方
        generalSelectOuter () {
            if(this.basicForm.businessTypeKey != 1 && this.basicForm.businessTypeKey != 5 && this.basicForm.businessTypeKey != 6) {
                this.clientPop('err', '临时需用计划或者事实合同才能选供方')
                return
            }
            let type = []
            let businessUnitTypes = []
            if(this.basicForm.businessTypeKey == 6) {
                type = [3]
                businessUnitTypes = [1]
            }
            if(this.basicForm.businessTypeKey == 1 || this.basicForm.businessTypeKey == 5) {
                type = [1, 2]
            }
            GeneralSelectOuter(type, [], businessUnitTypes).then(res=>{
                this.basicForm.supplierName = res.outerName
                this.basicForm.supplierId = res.id
                this.test = res
            })
        },
        //控制汇总明细的事件
        clickSelectContro (id) {
            this.showConnect = id
        },
        init () {
            this.getCurrentUnitInfo()
            this.getBasicInfo()
            this.getUserInfo()

            this.getDtlList()
            this.getwarehouseObj()//获取仓库
        },
        //获取本地登录信息
        getUserInfo () {
            const userInfo = JSON.parse(window.localStorage.getItem('vuex')).userInfo.orgInfo
            this.basicForm.orgId = userInfo.orgId
            this.basicForm.orgName = userInfo.orgName
        },
        changeBusinessType () {
            this.basicForm.sourceNo = null
            this.basicForm.sourceId = null
            this.basicForm.supplierName = null
            this.basicForm.supplierId = null
            if(this.detailedTableData.length > 0) {
                this.detailedTableData[0].children.forEach(item=>item.changeType = -1)
            }

            const obj =  this.businessTypeArr.find(item=>this.basicForm.businessTypeKey === item.id)
            this.basicForm.businessTypeValue = obj.name
        },
        getDtlList () {
            otherRequest.turnoverWarehousingFindByBillId(this.billId).then(res=>{
                if (res.length > 0) {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.businessType = this.basicForm.businessTypeKey

                        item.children.forEach(i => {
                            i.parentId = item.uuid
                            i.uuid = i.dtlId
                            i.changeType = 0
                        })

                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })

                    this.detailedTableData = res
                    console.log(res, 'res')

                }
            })
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/warehousing/findById',
                    params: {
                        billId: this.billId
                    }
                })
                .then(res => {
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                    }
                })
        },
        async selectreceivingPersonnelName () {
            const obj = await selectName()
            this.basicForm.receivingPersonnelName = obj.userName
            this.basicForm.receivingPersonnelId = obj.userId
        },
        linkToSouce () {
            if(this.basicForm.sourceId) {
                const linkData = {
                    '0': '/ctMaterialApplyShow', //物资采购合同（自购）
                    '1': '/momentNeedPlanShow', //临时需用计划（自购）
                    '2': '/revolveAllocationShow', //调拨
                    '3': '/ctRevolvMaterialApplyShow', //租赁合同
                    '4': '/revolveInternalLeaseTransferShow', //内租调动
                    '5': '/momentNeedPlanShow',
                }

                // 客户端弹窗弹出本地页面
                openAppClient(`${linkData[this.basicForm.businessTypeKey]}?billid=${this.basicForm.sourceId}&isview=true`, '查看源单',)

            }

        },
        // 选择人员
        async selectName () {
            const obj = await selectName()
            this.basicForm.purchaserName = obj.userName
            this.basicForm.purchaserId = obj.userId
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        otherRequest.turnoverWarehousingUpdate(this.basicForm).then(()=>{
                            this.getBasicInfo() //更新基本信息
                            resolve()
                        }).catch(err=>{
                            this.setError('baseInfo')
                            reject(err)
                        })
                    }
                    else {
                        this.setError('baseInfo')
                        this.scorllError()
                        reject()
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            if(this.detailedTableData.length > 0) {
                this.detailedTableData[0].businessType = this.basicForm.businessTypeKey
            }
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    otherRequest.turnoverWarehousingUpdateDtlList(this.detailedTableData).then(()=>{
                        this.getDtlList() //更新明细
                        resolve()
                    }).catch(err=>{
                        this.setError('detailed')
                        reject(err)
                    })
                }).catch(err=>{
                    this.setError('detailed')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                ]
            }
            submitCommit(this, requestFn)
        },

        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            showLoading()

            this.$Ajax
                .httpGet({
                    url: '/turnover/warehousing/delete',
                    params: { billId: this.billId },

                })
                .then(() => {
                    hideLoading()

                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },
        /**
         * 明细
         */
        // 选择物资
        async clickSingle () {
            if(this.basicForm.businessTypeKey == 6) {
                this.clientPop('err', '事实合同不可选源单！')
                return
            }

            await setTurnoverSelectInstockMaterials(this.detailedTableData, this.billId, Number(this.basicForm.businessTypeKey), this.basicForm.orgId,).then(res=>{
                this.detailedTableData = res.detailedTableData
                this.basicForm.sourceNo = res.data[0].billNo
                this.basicForm.sourceId = res.data[0].billId

                // 判断条件：合同和调拨才带出供方
                if (this.basicForm.businessTypeKey == 0 || this.basicForm.businessTypeKey == 3 || this.basicForm.businessTypeKey == 2) {
                    this.test = res.data
                    this.basicForm.supplierName = res.data[0].name
                    this.basicForm.supplierId = res.data[0].parentId
                }

                this.basicForm.totalQuantity = this.detailedTableData[0].children.reduce((a, b) => a + Number(b.receiptQuantity), 0)
                // 仓库
                let deepClone = [...this.detailedTableData]
                deepClone[0].children.forEach(v => {
                    v.warehouseId = this.warehouseObj.billId
                    v.warehouseName = this.warehouseObj.name
                })
                this.detailedTableData = deepClone
            })

        },
        // 选择基础库
        async clickBase () {
            this.test = this.basicForm.orgId
            const data = await categoryLibrary()
            if (data.length > 0) {

                // 更具OrgId获取仓库信息
                let warehouseObj = await otherRequest.getProjectDepartmentWarehouse(this.basicForm.orgId) || {}
                data.forEach(v => {
                    v.warehouseNameId = warehouseObj.billId
                    v.warehouseName = warehouseObj.name
                })

                const obj = doChildren(data, 'base', this.billId, this.basicForm.businessTypeKey)
                if(this.detailedTableData.length > 0) {
                    this.detailedTableData[0].children = this.detailedTableData[0].children.concat(...obj[0].children)
                }else{
                    this.detailedTableData = obj
                }
            }
        },
        async  getwarehouseObj () {
            // 更具OrgId获取仓库信息
            this.warehouseObj = await otherRequest.getProjectDepartmentWarehouse(this.basicForm.orgId) || {}
            console.log(this.warehouseObj, 'this.warehouseObj')
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.curRow = row
            if (row.dtlId) {
                this.curRow = row
                this.curRow.changeType = 2
            }
            this.collectCount()
        },
        collectCount () {
            this.basicForm.totalQuantity = 0
            this.detailedTableData.forEach(v => {
                v.children.forEach(item => {
                    if (item.changeType != -1) {
                        this.basicForm.totalQuantity += Number(item.receiptQuantity)
                    }
                })
            })
        },
        //点击删除的时候
        deleteEle (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    deleteLogic(row, $index, this, ['totalQuantity'])
                }
            )
        },
        /**
         * 审核
         */
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },
        handleClose () {
            this.$router.push('/revolveStorageList')
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            }else if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject)=>{

                this.errorMsg = []
                this.detailedTableData.forEach(v => {
                    v.children.forEach((item, index) => {
                        if (item.changeType !== -1) {
                            if (item.receiptQuantity === '' || item.receiptQuantity === null) {
                                let str = `请填写第 ${index + 1} 行的入库数量`
                                this.errorMsg.push(str)
                            }
                            if(this.isLease) { //租赁
                                if (item.timeUnit === '' || item.timeUnit === null) {
                                    let str = `请填写第 ${index + 1} 行的可调配数`
                                    this.errorMsg.push(str)
                                }
                                if (item.leaseTime === '' || item.leaseTime === null) {
                                    let str = `请填写第 ${index + 1} 行的可调配数`
                                    this.errorMsg.push(str)
                                }
                            }
                        }
                    })
                })

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()

                } else {
                    this.isErrorMsg = false
                    resolve()

                }
            })

        },

    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
  color: red;
}

.like {
  color: rgb(46, 97, 215);
  font-size: 17px;
  line-height: 30px;
  cursor: pointer;
}
.contro-line{
    display: flex;

}
.basicControItem{
        border-bottom: 0;
        padding: 8px;
        cursor: pointer;
         user-select:none;
        border: 1px solid #fff;

}
 .controItem{
        border: 1px solid #DBDBDB;
        background-color: #fff;
        border-bottom: 0;
        padding: 8px;
        border-radius: 4px 4px 0 0 ;
        cursor: pointer;
         user-select:none;
    }
</style>
